package com.frinder.seata.order.service;

import com.frinder.seata.data.base.BaseException;
import com.frinder.seata.data.base.Result;
import com.frinder.seata.data.domain.model.TbOrder;
import com.frinder.seata.data.domain.service.ITbOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @ClassName BizOrderService
 * @Description 订单服务
 * @Author frinder
 * @Date 2020/8/18 15:41
 * @Verion 1.0
 */
@Slf4j
@Service
public class BizOrderService {

    @Resource
    private ITbOrderService tbOrderService;

    @Resource
    private CallStorageService callStorageService;

    @Resource
    private CallAccountService callAccountService;

    @GlobalTransactional(name = "fsp-create-order", rollbackFor = {Exception.class, BaseException.class})
    public void create(TbOrder order, boolean timeout, boolean circle) {
        log.info(">> 客户下单");

        // 生成订单
        tbOrderService.save(order);
        log.info(">> 开始调用扣减库存服务");
        Result result = callStorageService.decrease(order.getProductId(), order.getCount());
        log.info("<< 扣减库存结果[{}]", result);

        log.info(">> 开始调用扣减账户余额服务");
        result = callAccountService.decrease(timeout, order.getUserId(), order.getMoney(), order.getId(), circle);
        log.info("<< 扣减余额结果[{}]", result);

        log.info("<< 下单结束");
    }

    public void completed(long orderId) {
        log.info(">> 完成订单[{}]", orderId);
        Optional.ofNullable(tbOrderService.findById(orderId))
                .ifPresent(o -> {
                    TbOrder order = TbOrder.builder()
                            .id(o.getId())
                            .status(2)
                            .build();
                    tbOrderService.update(order);
                });
    }
}
